package com.zero.manager_following.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.zero.manager_following.entity.User;
import com.zero.manager_following.mapper.UserMapper;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

/**
 * 功能：token验证工具
 * 作者：zero
 * 日期：2024/9/8 16:29
 */

public class TokenUtils {

    private static UserMapper staticUserMapper;

    @Resource
    UserMapper userMapper;

    @PostConstruct
    public void setUserService() {
        staticUserMapper = userMapper;
    }

    /**
     * 生成token
     *
     * @param userId
     * @param sign
     * @return
     */
    public static String generateToken(String userId, String sign) {
        return JWT.create().withAudience(userId) //将用户id保存到token里面，作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) //token有效期2小时
                .sign(Algorithm.HMAC256(sign)); //以password作为token的密钥
    }

    /**
     * 获取当前登录的用户信息
     *
     * @return user对象
     */
    public static User getCurrentUser() {
        try {
            HttpServletRequest request =
                    ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token)) {
                String userId = JWT.decode(token).getAudience().getFirst();
                return staticUserMapper.selectById(Integer.parseInt(userId));
            }
        } catch (JWTDecodeException | NumberFormatException e) {
            return null;
        }
        return null;
    }
}

